package com.gx.security.asymmetric;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.interfaces.DHPrivateKey;
import javax.crypto.interfaces.DHPublicKey;
import javax.crypto.spec.DHParameterSpec;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by gx on 2017/3/29.
 */
public class DHdemo {
    public static final String ALGORITHM = "DH";
    /**
     * 默认密钥字节数
     * <p>
     * <p>
     * <p>
     * DH
     * Default Keysize 1024
     * Keysize must be a multiple of 64, ranging from 512 to 1024 (inclusive).
     */
    private static final int KEY_SIZE = 1024;
    /**
     * DH加密下需要一种对称加密算法对数据加密，这里我们使用DES，也可以使用其他对称加密算法。
     */
    public static final String SECRET_ALGORITHM = "DES";
    private static final String PUBLIC_KEY = "DHPublicKey";
    private static final String PRIVATE_KEY = "DHPrivateKey";

    /**
     * 初始化甲方密钥
     *
     * @return
     * @throws Exception
     */
    public static Map initKey() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(KEY_SIZE);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 甲方公钥
        DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
// 甲方私钥
        DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();
        Map keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 初始化乙方密钥
     *
     * @param key 甲方公钥
     * @return
     * @throws Exception
     */
    public static Map initKey(String key) throws Exception {
        // 解析甲方公钥
        byte[] keyBytes = new BASE64Decoder().decodeBuffer(key);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
// 由甲方公钥构建乙方密钥
        DHParameterSpec dhParamSpec = ((DHPublicKey) pubKey).getParams();
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyFactory.getAlgorithm());
        keyPairGenerator.initialize(dhParamSpec);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
// 乙方公钥
        DHPublicKey publicKey = (DHPublicKey) keyPair.getPublic();
// 乙方私钥
        DHPrivateKey privateKey = (DHPrivateKey) keyPair.getPrivate();
        Map keyMap = new HashMap(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * 加密
     *
     * @param data       待加密数据
     * @param publicKey  甲方公钥
     * @param privateKey 乙方私钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String publicKey, String privateKey) throws Exception {
// 生成本地密钥
        SecretKey secretKey = getSecretKey(publicKey, privateKey);
// 数据加密
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        return new BASE64Encoder().encode(cipher.doFinal(data.getBytes("UTF-8")));
    }

    /**
     * 解密
     *
     * @param data       待解密数据
     * @param publicKey  乙方公钥
     * @param privateKey 乙方私钥
     * @return
     * @throws Exception
     */
    public static String decrypt(String data, String publicKey, String privateKey) throws Exception {
// 生成本地密钥
        SecretKey secretKey = getSecretKey(publicKey, privateKey);
// 数据解密
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decode_data = new BASE64Decoder().decodeBuffer(data);
        return new String(cipher.doFinal(decode_data));
    }

    /**
     * 构建密钥
     *
     * @param publicKey  公钥
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    private static SecretKey getSecretKey(String publicKey, String privateKey) throws Exception {
// 初始化公钥
        byte[] pubKeyBytes = new BASE64Decoder().decodeBuffer(publicKey);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKeyBytes);
        PublicKey pubKey = keyFactory.generatePublic(x509KeySpec);
// 初始化私钥
        byte[] priKeyBytes = new BASE64Decoder().decodeBuffer(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKeyBytes);
        Key priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        KeyAgreement keyAgree = KeyAgreement.getInstance(keyFactory.getAlgorithm());
        keyAgree.init(priKey);
        keyAgree.doPhase(pubKey, true);
// 生成本地密钥
        SecretKey secretKey = keyAgree.generateSecret(SECRET_ALGORITHM);
        return secretKey;
    }

    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map keyMap) throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return new BASE64Encoder().encode(key.getEncoded());
    }

    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return new BASE64Encoder().encode(key.getEncoded());
    }

    public static void main(String[] args) throws Exception {
        // 生成甲方密钥对儿
        Map aKeyMap = DHdemo.initKey();
        String aPublicKey = DHdemo.getPublicKey(aKeyMap);
        String aPrivateKey = DHdemo.getPrivateKey(aKeyMap);
        System.err.println("甲方公钥:" + aPublicKey);
        System.err.println("甲方私钥:" + aPrivateKey);
// 由甲方公钥产生本地(乙方)密钥对儿
        Map bKeyMap = DHdemo.initKey(aPublicKey);
        String bPublicKey = DHdemo.getPublicKey(bKeyMap);
        String bPrivateKey = DHdemo.getPrivateKey(bKeyMap);
        System.err.println("乙方公钥:" + bPublicKey);
        System.err.println("乙方私钥:" + bPrivateKey);
        String input = "DH算法测试";
        System.out.println("原文: " + input);
// 由甲方公钥，乙方私钥构建密文
        String aCode = DHdemo.encrypt(input, aPublicKey, bPrivateKey);
        System.out.println("由甲方公钥,乙方私钥构建密文: " + aCode);
// 由乙方公钥，甲方私钥解密
        String aDecode = DHdemo.decrypt(aCode, bPublicKey, aPrivateKey);
        System.out.println("由乙方公钥,甲方私钥解密: " + aDecode);
        System.err.println(" ===============反过来加密解密================== ");
// 由乙方公钥，甲方私钥构建密文
        String bCode = DHdemo.encrypt(input, bPublicKey, aPrivateKey);
        System.out.println("由乙方公钥,甲方私钥构建密文: " + bCode);
// 由甲方公钥，乙方私钥解密
        String bDecode = DHdemo.decrypt(bCode, aPublicKey, bPrivateKey);
        System.out.println("由甲方公钥,乙方私钥解密: " + bDecode);
/**
 * 如我代码证实，甲乙双方在获得对方公钥后可以对发送给对方的数据加密，同时也能对接收到的数据解密，达到了数据安全通信的目的！
 */
    }
}
